const db = wx.cloud.database()
const _ = db.command
const dishCollection = db.collection('dish')
/**
 * 获取菜品列表
 * @param params 查询参数
 * @returns 菜品列表
 */
export const getDishes = async (params : any = {}) => {
	const { keyword = '', categoryId = '', page, pageSize } = params;
	let where : any = {}
	let dishList = []
	try {
		if (categoryId) {
			where.categoryId = categoryId
		}

		if (keyword) {
			where.name = db.RegExp({ regexp: keyword });
		}

		if (!where.name && !where.categoryId) {
			where = { name: _.exists(true) }
		}

		if (!page && !pageSize) {
			for (var i = 0; ; i += 20) {
				const { data: list } = await dishCollection.where(where).orderBy('createTime', 'desc').skip(i).limit(20).get()
				if (list.length === 0) break
				dishList.push(...list)
				if (list.length < 20) break
			}
		} else {
			const skip = (page - 1) * pageSize;
			({ data: dishList } = await dishCollection
				.where(where)
				.orderBy('createTime', 'desc')
				.skip(skip)
				.limit(pageSize)
				.get());
		}
		return dishList;
	} catch (error) {
		wx.showToast({ title: error.message || '数据获取失败', icon: 'none' })
		console.error('获取菜品列表失败:', error);
		throw error;
	}
};

/**
 * 添加菜品
 * @param dish 菜品数据
 * @returns 添加结果
 */
export const addDish = async (dish : any) => {
	const { dishFlavors, ...data } = dish
	let _id : string | number;
	try {
		wx.showLoading({ title: '稍等...', mask: true });
		const { total } = await db.collection('setmeal').where({ name: dish.name }).count();
		if (total) {
			throw new Error('名称与套餐名称重复')
		}
		({ _id } = await db.collection('dish').add({ data: { ...data, createTime: db.serverDate(), updateTime: db.serverDate() } }));
		if (dishFlavors.length > 0) {
			for (let item of dishFlavors) {
				await db.collection('dish_flavor').add({
					data: {
						dishId: _id,
						name: item.name,
						value: JSON.stringify(item.value)
					}
				})
			}
		}
		wx.hideLoading()
	} catch (error) {
		await wx.hideLoading()
		// 事务管理
		if (_id) {
			await dishCollection.doc(_id).remove()
			const { data } = await db.collection('dish_flavor').field({ _id: true }).where({ dishId: _id }).get()
			await Promise.all(data.map(item => db.collection('dish_flavor').doc(item._id).remove()))
		}
		wx.showToast({ title: '添加失败，检查菜品名称是否有重复', icon: 'none' })
		console.error('添加菜品失败:', error);
		throw error;
	}
};

/**
 * 更新菜品
 * @param dish 菜品数据
 * @returns 更新结果
 * 下架菜品的同时要下架此菜关联的套餐 todo
 */
export const updateDish = async (dish : any) => {
	const { _id, dishFlavors, ...data } = dish;
	try {
		wx.showLoading({ title: '更新中...', mask: true })
		const { total } = await db.collection('setmeal').where({ name: dish.name }).count();
		if (total) {
			throw new Error('名称与套餐名称重复')
		}
		await db.collection('dish').doc(_id).update({ data: { ...data, updateTime: db.serverDate() } });
		if (dishFlavors) {
			const { data: list } = await db.collection('dish_flavor').field({ _id: true }).where({ dishId: _id }).get()
			await Promise.all(list.map(item => db.collection('dish_flavor').doc(item._id).remove()))
			if (dishFlavors.length > 0) {
				await Promise.all(dishFlavors.map(item => db.collection('dish_flavor').add({
					data: {
						dishId: _id,
						name: item.name,
						value: JSON.stringify(item.value)
					}
				})))
			}
		}
		wx.hideLoading()
	} catch (error) {
		await wx.hideLoading()
		wx.showToast({ title: error.message || '更新失败', icon: 'error' })
		console.error('更新菜品失败:', error);
		throw error;
	}
};
// 修改启售停售状态
export const updateDishStatus = async (dish : any) => {
	const { _id, status } = dish
	try {
		wx.showLoading({ title: '稍等...', mask: true })
		if (status === 0) {
			const { data: list } = await db.collection('setmeal_dish').field({ setmealId: true, _id: false }).where({ dishId: _id }).get()
			if (list.length > 0) {
				const setmeals = [...new Set(list.map(item => item.setmealId))]
				await Promise.all(setmeals.map(item => db.collection('setmeal').doc(item).update({ data: { status: 0 } })))
			}
		}
		await dishCollection.doc(_id).update({ data: { status } })
		wx.hideLoading()
	} catch (error) {
		await wx.hideLoading()
		wx.showToast({ title: error.message || "操作失败", icon: 'none' })
		throw error
	}
}

/**
 * 删除菜品
 * @param id 菜品ID
 * @returns 删除结果
 */
export const deleteDish = async (id : string, image : string) => {
	try {
		wx.showLoading({ title: '删除中...', mask: true })
		const { total } = await db.collection('setmeal_dish').where({ dishId: id }).count()
		if (total) {
			throw new Error('有关联的套餐，不能删除')
		}
		// 先删除关联的口味数据
		const { data: list } = await db.collection('dish_flavor').field({ _id: true }).where({ dishId: id }).get()
		await Promise.all(list.map(item => db.collection('dish_flavor').doc(item._id).remove()))
		// 删除云存储中的图片
		await wx.cloud.deleteFile({ fileList: [image] })
		// 再删除菜品
		const res = await db.collection('dish').doc(id).remove();
		wx.hideLoading()
		return res;
	} catch (error) {
		await wx.hideLoading()
		wx.showToast({ title: error.message || '删除失败', icon: 'none' })
		console.error('删除菜品失败:', error);
		throw error;
	}
};

/**
 * 获取菜品口味
 * @param dishId 菜品ID
 * @returns 口味列表
 */
export const getDishFlavors = async (dishId : string) => {
	try {
		const res = await db.collection('dish_flavor').where({ dishId }).get();
		return res.data
	} catch (error) {
		console.error('获取菜品口味失败:', error);
		wx.showToast({ title: '获取菜品口味失败', icon: 'none' })
		throw error;
	}
};